#!/usr/bin/env python3
"""청구항변반박전략서.md에서 complaint_information.md를 생성한다."""

from __future__ import annotations

import re
import sys
from pathlib import Path


BASE_DIR = Path(__file__).resolve().parent
INPUT_PATH = BASE_DIR / "청구항변반박전략서.md"
OUTPUT_PATH = BASE_DIR / "complaint_information.md"

MASTER_SECTION_HEADER = "## 3. 청구 마스터 표"
OVERVIEW_HEADER = "### 3.1 청구권 개요"
DETAIL_HEADER = "### 3.2 개별 청구권 상세 정보"
NEXT_TOP_LEVEL_HEADER_PATTERN = re.compile(r"^##\s+\d+\.", re.MULTILINE)
DETAIL_BLOCK_PATTERN = re.compile(
    r"(?ms)^(####\s+C-\d{3}:.*?\n\n<div class=\"full-width-table-wrap\".*?</div>)\s*"
)


def read_markdown(path: Path) -> str:
    try:
        return path.read_text(encoding="utf-8")
    except FileNotFoundError as exc:
        raise RuntimeError(f"입력 파일을 찾을 수 없습니다: {path}") from exc


def find_section_bounds(text: str, start_header: str, end_header: str | None = None) -> tuple[int, int]:
    start = text.find(start_header)
    if start == -1:
        raise RuntimeError(f"헤더를 찾을 수 없습니다: {start_header}")

    section_start = start + len(start_header)
    if end_header:
        end = text.find(end_header, section_start)
        if end == -1:
            raise RuntimeError(f"종료 헤더를 찾을 수 없습니다: {end_header}")
        return section_start, end

    match = NEXT_TOP_LEVEL_HEADER_PATTERN.search(text, section_start)
    if not match:
        return section_start, len(text)
    return section_start, match.start()


def extract_first_table_block(section_text: str, context_name: str) -> str:
    div_start = section_text.find('<div class="full-width-table-wrap"')
    if div_start == -1:
        raise RuntimeError(f"{context_name}에서 표 블록 시작을 찾을 수 없습니다.")

    div_end = section_text.find("\n</div>", div_start)
    if div_end == -1:
        raise RuntimeError(f"{context_name}에서 표 블록 종료를 찾을 수 없습니다.")

    return section_text[div_start : div_end + len("\n</div>")].strip()


def extract_overview_table(master_section_text: str) -> str:
    start, end = find_section_bounds(master_section_text, OVERVIEW_HEADER, DETAIL_HEADER)
    overview_section = master_section_text[start:end]
    return extract_first_table_block(overview_section, "청구권 개요")


def extract_detail_blocks(master_section_text: str) -> list[str]:
    start, end = find_section_bounds(master_section_text, DETAIL_HEADER)
    detail_section = master_section_text[start:end]
    blocks = [match.group(1).strip() for match in DETAIL_BLOCK_PATTERN.finditer(detail_section)]
    if not blocks:
        raise RuntimeError("개별 청구권 상세 정보 블록을 찾을 수 없습니다.")
    return blocks


def assemble_document(overview_table: str, detail_blocks: list[str]) -> str:
    parts = [
        "# 청구상세정보",
        "",
        "## 1. 청구권 개요",
        "",
        overview_table,
        "",
        "## 2. 개별 청구권 상세 정보",
        "",
        "\n\n".join(detail_blocks),
        "",
    ]
    return "\n".join(parts)


def write_markdown(path: Path, content: str) -> None:
    path.write_text(content, encoding="utf-8")


def main() -> None:
    print(f"[stage5] reading: {INPUT_PATH}", file=sys.stderr)
    source_text = read_markdown(INPUT_PATH)

    master_start, master_end = find_section_bounds(source_text, MASTER_SECTION_HEADER)
    master_section_text = source_text[master_start:master_end]

    overview_table = extract_overview_table(master_section_text)
    detail_blocks = extract_detail_blocks(master_section_text)
    output_text = assemble_document(overview_table, detail_blocks)

    write_markdown(OUTPUT_PATH, output_text)
    print(
        f"[stage5] saved: {OUTPUT_PATH} "
        f"(overview=1, detail_blocks={len(detail_blocks)})",
        file=sys.stderr,
    )


if __name__ == "__main__":
    main()
